package com.baidu.customview.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.EditText;

import com.baidu.customview.R;
import com.baidu.customview.utils.MetricsUtils;


/**
 * Created by Kvin on 2015/12/31.
 */
public class BottomLineEditText extends EditText{
    private Paint paint;
    private int lineLength;
    private final double SCALE=5.51;
    public BottomLineEditText(Context context) {
        super(context);
        initData(context);
    }

    private void initData(Context context) {
        paint = new Paint();
        paint.setColor(context.getResources().getColor(R.color.blue));
        paint.setStrokeWidth(3);
        setLineWidth(getText().toString());
    }

    //set lineWidth for drawing
    public void setLineWidth(String txt) {
        Rect rect = new Rect();
        paint.getTextBounds(txt, 0, txt.length(), rect);
        int mw= (int) (rect.width()*SCALE);
        if (this.getWidth() > mw) {
            lineLength = this.getWidth() - 1;
        } else {
            lineLength = mw - 1;
        }
//        lineLength= this.getWidth()>paint.measureText(txt)?this.getWidth(): (int) paint.measureText(txt);
//
        lineLength= MetricsUtils.conMetrics(getRootView()).getMeasuredWidth();
//        Log.e("length","================="+lineLength+"|||||>"+paint.measureText(txt)+"|||"+rect.width());
        invalidate();
    }

    public BottomLineEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        initData(context);
    }

    public BottomLineEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initData(context);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawLine(1, this.getHeight() - 1, lineLength, this.getHeight() - 1, paint);
    }




}
